package scsys.servlet;

import scsys.mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import scsys.pojo.User;
import scsys.util.SqlSessionFactoryUtils;

import java.util.List;

public class UserServiceImpl implements UserService {
    //1. 创建SqlSessionFactory 工厂对象
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();


    @Override
    public void add(User user) {
        //2. 获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //4. 调用方法
        mapper.add(user);
        // 5、提交事務
        sqlSession.commit();
        //5. 释放资源
        sqlSession.close();
    }

    @Override
    public List<User> selectMore(User user) {
        //2. 获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //4. 调用方法
        List<User> users = null;
        users = mapper.selectMore(user);

        //5. 释放资源
        sqlSession.close();

        return users;
    }

    @Override
    public User selectOne(User user) {
        //2. 获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //4. 调用方法
        User selectUser = null;
        selectUser = mapper.selectOne(user);

        //5. 释放资源
        sqlSession.close();

        return selectUser;
    }

    @Override
    public List<User> selectAll() {
        //2. 获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //4. 调用方法
        List<User> users = null;
        users = mapper.selectAll();

        //5. 释放资源
        sqlSession.close();
        return users;
    }

    @Override
    public void deleteUser(User user) {
        //2. 获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //4. 调用方法
        mapper.deleteUser(user);
        // 5、提交事務
        sqlSession.commit();
        //5. 释放资源
        sqlSession.close();
    }
}
